<?php

class MemberController extends MemberBaseController
{
    /**
     * Declares class-based actions.
     */
    public function actions()
    {
    }


    public function actionIndex()
    {
        Request::redirect('form');
    }


    public function actionForm( $where=null )
    {
        $userId = SessionManager::getValue('userId');
        if( $userId ) {
            // 若已登入, 直接導到 admin/index (並未檢查是否有登入權限)
            Request::redirect('admin/index');
        }

        $this->render('form', Array('where'=>$where) );
    }


    public function actionLogin( $where=null )
    {
        $data = Array(
            'where'=>$where
        );

        SessionManager::clear();

        $posts = Request::getPostInfo();
        if( !$posts ) {
            $this->render('form', $data );
            return;
        }

        $userIdentities = FactoryUserIdentities::factory();
        $user = $userIdentities->authenticate( $posts['name'], $posts['password'] );
        if( !$user ) {
            $data['showErrorMessages'] = '帳號或密碼錯誤';
            $this->render('form', $data );
            return;
        }
        SessionManager::setValue( 'userId', $user->getId() );


        // 設定使用者使用的 service
        $serviceManager = new ServiceManager();
        $serviceManager->setSessionManager( new SessionManager() );
        $serviceManager->resetUserServicesByDatabase( $user->getId() );
        $serviceManager->saveToSession();

        // 
        $this->_setUserPermissionsToSession( $user );

        // check permissions
        $permissionManager = new PermissionManager();
        $permissionManager->setSessionManager( new SessionManager() );
        if( !$permissionManager->checkRole('work_login') ) {
            SessionManager::clear();
            $data['showErrorMessages'] = '該帳號沒有登入的權限';
            $this->render('form', $data );
            return;
        }

        // TODO: 在 session 中寫入 user ip, browser info, 以避免 session id (cookie) 被它人盜用 )
        // 並且每次連線做檢查!
        // ....
        SessionManager::setValue( 'loginInfoString',
            $user->getId() .'_'.
            $_SERVER['REMOTE_ADDR'] .'_'.
            $_SERVER['HTTP_USER_AGENT']
        );

        if( 'goBlog'==$where ) {

            $blog = $serviceManager->getFocusBlog();
            if( $blog ) {
                Request::redirect( 'blog/'.$blog->getId() );
            }

        }

        //            
        Request::redirect('admin/index');

    }


    public function actionLogout()
    {
        SessionManager::clear();
        Request::redirect('site/index');
    }


    /**
     *  設定使用者使用的 permission
     */
    protected function _setUserPermissionsToSession( $user )
    {
        $permissionLinks = new UserPermissionCategoryLinks();

        $permissionCategories = new UserPermissionCategories();
        $myPermissionLinks = $permissionCategories->getUserPermissionCategoriesByUserId( $user->getId() );
        if( !$myPermissionLinks ) {
            return false;
        }

        $permissions = Array();
        foreach( $myPermissionLinks as $myPermissionLink ) {
            $permissions['ids'][]   = $myPermissionLink->getId();
            $permissions['keys'][]  = $myPermissionLink->getKeyName();
            // 名稱會變動, 不建議使用, 目前留著的用意是方便 debug 的時候看到文字
            $permissions['names'][] = $myPermissionLink->getName();
        }

        SessionManager::setValue( 'permissions', $permissions );
    }

}